<?php

namespace App\Http\Controllers\Test;

use Illuminate\Http\Request;
use Laravel\Passport\TokenRepository;
use Lcobucci\JWT\Parser as JwtParser;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response as Psr7Response;
use League\OAuth2\Server\AuthorizationServer;
use Laravel\Passport\Http\Controllers\HandlesOAuthErrors;

class AccessTokenController extends Controller
{
    use HandlesOAuthErrors;

    /**
     * The authorization server.
     *
     * @var \League\OAuth2\Server\AuthorizationServer
     */
    protected $server;

    /**
     * The token repository instance.
     *
     * @var \Laravel\Passport\TokenRepository
     */
    protected $tokens;

    /**
     * The JWT parser instance.
     *
     * @var \Lcobucci\JWT\Parser
     */
    protected $jwt;

    /**
     * Create a new controller instance.
     *
     * @param \League\OAuth2\Server\AuthorizationServer $server
     * @param \Laravel\Passport\TokenRepository         $tokens
     * @param \Lcobucci\JWT\Parser                      $jwt
     *
     * @return void
     */
    public function __construct(AuthorizationServer $server,
                                TokenRepository $tokens,
                                JwtParser $jwt)
    {
        $this->jwt    = $jwt;
        $this->server = $server;
        $this->tokens = $tokens;
    }

    /**
     * Authorize a client to access the user's account.
     *
     * @param \Psr\Http\Message\ServerRequestInterface $request
     *
     * @return \Illuminate\Http\Response
     */
    public function issueToken(ServerRequestInterface $request)
    {//dd(md5('123456iOi0vv'));
        return $this->withErrorHandling(function () use ($request) {
            return $this->convertResponse(
                $this->server->respondToAccessTokenRequest($request, new Psr7Response)
            );
        });
    }

    /**
     * 内部服务发放测试.
     */
    public function test(Request $request)
    {
//        $server = app(\League\OAuth2\Server\AuthorizationServer::class);
//        dd($server);
//
//        $request->withParsedBody([
//            'grant_type' => 'password',
//            'client_id' => '2',
//            'client_secret' => 'IhHPYDk2AiWlgTeXWFkB4JVHar1VruhEpbBbVIHR',
//            'username' => '13857173334',
//            'password' => '123456',
//            'scope' => ''
//        ]);
//
//
//        $request->withAttribute('grant_type', 'password');
//
//        dd($request->getParsedBody());
//
//        return $server->respondToAccessTokenRequest($request, new Psr7Response);
    }
}
